iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 20
0
自我挑戰組

純新手學習 JavaScript系列 第 20

新手學習JavaScript:day20 - Sum of Even Numbers After Queries

  • 分享至 

  • xImage
  •  

直接來上今天的題目:

/* 
We have an array A of integers, and an array queries of queries.

For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index].  Then, the answer to the i-th query is the sum of the even values of A.

(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)

Return the answer to all queries.  Your answer array should have answer[i] as the answer to the i-th query.

 

Example 1:

Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation: 
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
*/
var sumEvenAfterQueries = function(A, queries) {
   
};

今天這題的題目給的相當詳細,傳入兩個陣列,一個是單純數字陣列,另一個是包含了值與索引所組合的陣列。最後輸出每一次修改後偶數的總和的陣列。

思考:

  1. 最後輸出一個陣列結果,我們可以先準備一個空陣列。
var sumEvenAfterQueries = function(A, queries) {
   let result = []
   return result
};
  1. A數字陣列會經過一次查詢而修改,queries有多長最後輸出的結果就多長。可以先從queries著手,讓它跑回圈。
var sumEvenAfterQueries = function(A, queries) {
   let result = []
  queries.forEach((query)=>{
         
  })
  return result
};
  1. 針對每一次query 我們可以修改A陣列,並且將A的偶數篩選出來做加總,並且將最後將結果丟給一開始準備的空陣列。
var sumEvenAfterQueries = function(A, queries) {
   let result = []
   let evenA
  queries.forEach((query)=>{
       A[query[1]] += query[0]
       evenA = A.filter((num)=> num % 2 === 0)
      result.push(evenA.reduce((sum, num)=>{return sum + num}))   
       
  })
  return result
};
  1. 如果evenA篩選出來並沒有任何偶數,再塞一個0進去
var sumEvenAfterQueries = function(A, queries) {
   let result = []
   let evenA
  queries.forEach((query)=>{
       A[query[1]] += query[0]
       evenA = A.filter((num)=> num % 2 === 0)
      if (evenA.length === 0){
        evenA[0] = 0
      }
      result.push(evenA.reduce((sum, num)=>{return sum + num}))   
       
  })
  return result
};

以上是今天的內容,寫法上有非常大的進步空間。如果有哪位大大路過經過,還請多多指教。


上一篇
新手學習JavaScript:day19 - Maximum Product of Three Numbers
下一篇
新手學習JavaScript:day21 - Max Consecutive Ones
系列文
純新手學習 JavaScript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言